package controllers

import dao._
import implicits.Implicits._
import play.api.libs.json.Json
import play.api.mvc.{AbstractController, ControllerComponents}
import tool.{FormTool, Tool}
import utils.Utils

import java.io.File
import java.nio.file.Files
import javax.inject.Inject
import scala.collection.immutable.SeqMap
import scala.concurrent.ExecutionContext.Implicits.global

/**
 * Created by yz on 11/5/2020
 */
class MapController @Inject()(cc: ControllerComponents)(
  implicit val prokaryoteDao: ProkaryoteDao,
  implicit val bioSampleDao: BioSampleDao,
  implicit val assemblyDao: AssemblyDao,
) extends AbstractController(cc) {

  def toIndex = Action { implicit request =>
    Ok(views.html.map.index())
  }

  def getCountryInfo = Action.async { implicit request =>
    bioSampleDao.selectAllLocation.map { locations =>
      val trueLocationMap = SeqMap("USA" -> "United States of America")
      val trueLocations = locations.map { location =>
        location.mySplit(":").head
      }
      val countryMap = trueLocations.groupMap(x => x)(y => y).map { case (k, vs) => (k, vs.size) }.
        map { case (k, v) =>
          val trueK = trueLocationMap.getOrElse(k, k)
          Json.obj("key" -> trueK, "num" -> v)
        }.toList
      Ok(Json.toJson(countryMap))
    }
  }

  def getProkaryoteByCountry = Action.async { implicit request =>
    val data = FormTool.countryForm.bindFromRequest().get
    val country = if (data.country == "United States of America") "USA" else data.country
    bioSampleDao.selectAll(country).flatMap { bioSamples =>
      prokaryoteDao.selectByBioSamples(bioSamples)
    }.map { x =>
      val array = Utils.getArrayByTs(x)
      Ok(Json.toJson(array))
    }
  }

}
